package com.sleep.psy.external_server.business.evaluation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sleep.psy.external_server.business.adjustment.entity.vo.GenerateSleepPlanReq;
import com.sleep.psy.external_server.business.adjustment.service.AdjustmentPlanService;
import com.sleep.psy.external_server.business.evaluation.entity.EvaluationRecord;
import com.sleep.psy.external_server.business.evaluation.entity.EvaluationReport;
import com.sleep.psy.external_server.business.evaluation.entity.dto.Res;
import com.sleep.psy.external_server.business.evaluation.entity.sleep.SubGeneralScaleReq;
import com.sleep.psy.external_server.business.evaluation.entity.sleep.SubQuestionReq;
import com.sleep.psy.external_server.business.evaluation.entity.sleep.SubSleepReq;
import com.sleep.psy.external_server.business.evaluation.entity.sleep.SubSleepScaleReq;
import com.sleep.psy.external_server.business.evaluation.mapper.EvaluationRecordMapper;
import com.sleep.psy.external_server.business.evaluation.mapper.EvaluationReportMapper;
import com.sleep.psy.external_server.business.evaluation.service.DealQuestionService;
import com.sleep.psy.external_server.business.evaluation.service.EvaluationRecordService;
import com.sleep.psy.external_server.business.evaluation.service.EvaluationReportService;
import com.sleep.psy.external_server.business.main.entity.MainUser;
import com.sleep.psy.external_server.business.main.service.MainUserService;
import com.sleep.psy.external_server.business.psy.mapper.PsyAnswerMapper;
import com.sleep.psy.external_server.business.psy.mapper.PsyContentMapper;
import com.sleep.psy.external_server.business.psy.mapper.PsyScoreMapper;
import com.sleep.psy.external_server.business.psy.mapper.PsySectionMapper;
import com.sleep.psy.external_server.constants.MySqlConstant;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sleep.psy.external_server.property.SleepProperties;
import com.sleep.psy.external_server.result.Result;
import com.sleep.psy.external_server.result.ResultEnum;
import com.sleep.psy.external_server.result.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 测评记录 服务实现类
 * </p>
 *
 * @author wenliguo
 * @since 2025-08-12
 */
@Service
public class EvaluationRecordServiceImpl extends ServiceImpl<EvaluationRecordMapper, EvaluationRecord> implements EvaluationRecordService {

    protected Logger logger = LoggerFactory.getLogger(EvaluationRecordService.class);

    @Autowired
    private EvaluationRecordMapper evaluationRecordMapper;

    @Autowired
    private EvaluationReportMapper evaluationReportMapper;

    @Autowired
    private MainUserService mainUserService;

    @Autowired
    private PsyAnswerMapper psyAnswerMapper;

    @Autowired
    private PsyContentMapper psyContentMapper;

    @Autowired
    private PsyScoreMapper psyScoreMapper;

    @Autowired
    private PsySectionMapper psySectionMapper;

    @Autowired
    private DealQuestionService dealQuestionService;

    @Autowired
    private AdjustmentPlanService adjustmentPlanService;

    @Autowired
    private EvaluationReportService reportService;

    @Autowired
    private SleepProperties sleepProperties;

    /**
     * 提交匹兹堡测评记录
     * @author wenliguo
     * @date 2025/6/6 09:18
     * @param req 请求
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result subSleepScale(SubSleepScaleReq req) {

        MainUser user = mainUserService.selectById(req.getUserId());
        if (null == user) {
            return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
        }

        EvaluationRecord record = new EvaluationRecord();
        record.setUserId(user.getId());
        record.setSchemeId(req.getSchemeId());
        record.setScaleId(req.getScaleId());
        record.setProcessId(req.getProcessId());
        record.setStartTime(req.getStartTime());
        record.setEndTime(req.getEndTime());
        record.setRecordDetails(req.getAnswer());
        evaluationRecordMapper.insert(record);

        EvaluationReport report = new EvaluationReport();
        report.setRecordId(record.getId());
        evaluationReportMapper.insert(report);

        dealQuestionService.subSleepAnswer(req, report.getId());

        reportService.professionalSleepReport(report.getId());
        return ResultUtil.success(report.getId());
    }

    /**
     * 通用量表提交
     * @author wenliguo
     * @date 2025/7/23 10:12
     * @param req 请求参数
     * @return com.sleep.psy.main_server.result.Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result subGeneralScale(SubGeneralScaleReq req) {
        MainUser user = mainUserService.selectById(req.getUserId());
        if (null == user) {
            return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
        }

        EvaluationRecord record = new EvaluationRecord();
        record.setUserId(user.getId());
        record.setScaleId(req.getScaleId());
        record.setProcessId(req.getProcessId());
        record.setStartTime(req.getStartTime());
        record.setEndTime(req.getEndTime());
        record.setRecordDetails(req.getAnswer());
        evaluationRecordMapper.insert(record);

        EvaluationReport report = new EvaluationReport();
        report.setRecordId(record.getId());
        evaluationReportMapper.insert(report);

        dealQuestionService.subGeneralScale(req, report.getId());

        reportService.generalReport(report.getId());
        return ResultUtil.success(report.getId());
    }

    /**
     * 提交isi测评记录
     * @author wenliguo
     * @date 2025/7/9 16:46
     * @param req 请求
     * @return com.sleep.psy.main_server.result.Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result subIsi(SubSleepScaleReq req) {
        MainUser user = mainUserService.selectById(req.getUserId());
        if (null == user) {
            return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
        }

        EvaluationRecord record = new EvaluationRecord();
        record.setUserId(user.getId());
        record.setSchemeId(req.getSchemeId());
        record.setScaleId(req.getScaleId());
        record.setProcessId(req.getProcessId());
        record.setAudioSort(req.getAudioSort());
        record.setStartTime(req.getStartTime());
        record.setEndTime(req.getEndTime());
        record.setRecordDetails(req.getAnswer());
        evaluationRecordMapper.insert(record);

        EvaluationReport report = new EvaluationReport();
        report.setRecordId(record.getId());
        evaluationReportMapper.insert(report);

        dealQuestionService.subIsi(req, report.getId());
        reportService.simpleIsiReport(report.getId());
        return ResultUtil.success(report.getId());
    }

    /**
     * 提交睡眠问卷记录
     * @author wenliguo
     * @date 2025/6/6 14:50
     * @param req 请求
     * @return com.sleep.psy.main_server.result.Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result subSleepQuestion(SubQuestionReq req) {
        MainUser user = mainUserService.selectById(req.getUserId());
        if (null == user) {
            return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
        }

        EvaluationRecord record = new EvaluationRecord();
        record.setUserId(user.getId());
        record.setSchemeId(req.getSchemeId());
        record.setScaleId(req.getScaleId());
        record.setTypes(req.getTypes());
        record.setProcessId(req.getProcessId());
        record.setStartTime(req.getStartTime());
        record.setEndTime(req.getEndTime());
        record.setRecordDetails(req.getAnswer());
        evaluationRecordMapper.insert(record);

        EvaluationReport report = new EvaluationReport();
        report.setRecordId(record.getId());
        evaluationReportMapper.insert(report);

        dealQuestionService.subSleepQuestionAnswer(req, report.getId());
        //生成调节方案
        GenerateSleepPlanReq planReq = new GenerateSleepPlanReq();
        planReq.setRecordId(record.getId());
        planReq.setUserId(req.getUserId());
        planReq.setSchemeId(req.getSchemeId());
        adjustmentPlanService.generateSleepPlan(planReq);
        return ResultUtil.success(record.getId());
    }

    /**
     * 通过用户id和量表id获取测评记录
     * @author wenliguo
     * @date 2025/6/17 14:48
     * @param userId 用户id
     * @param scaleId 量表id
     * @return java.util.List<com.sleep.psy.main_server.business2.evaluation.entity.EvaluationRecord>
     */
    @Override
    public List<EvaluationRecord> selectRecordsByUserIdScaleId(Long userId, Integer scaleId) {
        QueryWrapper<EvaluationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("scale_id", scaleId)
                .eq("status", MySqlConstant.STATUS_1);
        return evaluationRecordMapper.selectList(wrapper);
    }

    /**
     * 通过测评记录id和用户id获取有效测评记录
     * @author wenliguo
     * @date 2025/6/9 11:29
     * @param id 测评记录id
     * @param userId 用户id
     * @return com.sleep.psy.main_server.business2.evaluation.entity.EvaluationRecord
     */
    @Override
    public EvaluationRecord selectRecord(Long id, Long userId) {
        QueryWrapper<EvaluationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id)
                .eq("user_id", userId)
                .eq("status", MySqlConstant.STATUS_1);
        return evaluationRecordMapper.selectOne(wrapper);
    }


    /**
     * 通过用户id判断用户是否答过失眠问卷和睡眠问卷
     * @author wenliguo
     * @date 2025/8/27 17:19
     * @param userId 用户id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result isAnswerQuestion(Long userId) {
        boolean sleeplessFlag = false;
        boolean sleepFlag = false;

        //失眠问卷
        QueryWrapper<EvaluationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("scale_id", sleepProperties.getSleeplessQuestionScale())
                .eq("status", MySqlConstant.STATUS_1);
        Integer count = evaluationRecordMapper.selectCount(wrapper);
        if (count > 0) {
            sleeplessFlag = true;
        }

        //睡眠问卷
        QueryWrapper<EvaluationRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("scale_id", sleepProperties.getSleepQuestionScale())
                .eq("status", MySqlConstant.STATUS_1);

        Integer integer = evaluationRecordMapper.selectCount(queryWrapper);
        if (integer > 0) {
            sleepFlag = true;
        }

        HashMap<String, Boolean> map = new HashMap<>();
        map.put("sleeplessFlag", sleeplessFlag);
        map.put("sleepFlag", sleepFlag);

        return ResultUtil.success(map);
    }

    /**
     * 通过用户id获取失眠问卷记录
     * @author wenliguo
     * @date 2025/8/27 17:32
     * @param userId 用户id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result selectSleeplessRecordByUserId(Long userId) {
        QueryWrapper<EvaluationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("scale_id", sleepProperties.getSleeplessQuestionScale())
                .eq("status", MySqlConstant.STATUS_1)
                .orderByDesc("id");
        List<EvaluationRecord> records = evaluationRecordMapper.selectList(wrapper);
        if (records.isEmpty()) {
            return ResultUtil.success();
        }

        return ResultUtil.success(records.get(0));
    }

    /**
     * 通过量表id和用户id判断用户是否答过该量表
     * @author wenliguo
     * @date 2025/8/28 09:45
     * @param scaleId 量表id
     * @param userId 用户id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result isAnswer(Integer scaleId, Long userId) {

        QueryWrapper<EvaluationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("scale_id", scaleId)
                .eq("status", MySqlConstant.STATUS_1)
                .orderByDesc("id")
                .last("limit 1");
        EvaluationRecord record = evaluationRecordMapper.selectOne(wrapper);
        if (null != record) {
            Long recordId = record.getId();
            QueryWrapper<EvaluationReport> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("record_id", recordId)
                    .eq("status", MySqlConstant.STATUS_1)
                    .orderByDesc("id")
                    .last("limit 1");
            EvaluationReport report = evaluationReportMapper.selectOne(queryWrapper);
            if (null == report) {
                return ResultUtil.success();
            }
            return ResultUtil.success(report.getId());
        }

        return ResultUtil.success();
    }

    /**
     * 提交失眠问卷
     * @author wenliguo
     * @date 2025/8/28 15:29
     * @param req 请求
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result subSleepLessScale(SubGeneralScaleReq req) {
        MainUser user = mainUserService.selectById(req.getUserId());
        if (null == user) {
            return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
        }

        EvaluationRecord record = new EvaluationRecord();
        record.setUserId(user.getId());
        record.setScaleId(req.getScaleId());
        record.setProcessId(req.getProcessId());
        record.setStartTime(req.getStartTime());
        record.setEndTime(req.getEndTime());
        record.setRecordDetails(req.getAnswer());
        evaluationRecordMapper.insert(record);

        EvaluationReport report = new EvaluationReport();
        report.setRecordId(record.getId());
        evaluationReportMapper.insert(report);
        dealQuestionService.subSleepLessScale(req, report.getId());
        reportService.generateSleeplessReport(user,record,report.getId());
        return ResultUtil.success(report.getId());
    }

    /**
     * 判断是否答过睡眠评估
     * @author wenliguo
     * @date 2025/9/8 11:04
     * @param req 请求参数
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result subSleep(SubSleepReq req) {
        Integer audioSort = req.getAudioSort();
        Long userId = req.getUserId();

        QueryWrapper<EvaluationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("audio_sort", audioSort)
                .eq("user_id", userId);

        List<EvaluationRecord> records = evaluationRecordMapper.selectList(wrapper);
        if (records.isEmpty()) {
            return ResultUtil.success(false);
        }

        return ResultUtil.success(true);

    }
}
